<template>
  <div class="app-container">
    <!-- 过滤 -->
    <div class="filter-container">
      <el-input v-model="listQuery.id" placeholder="合同编号" style="width: 200px;" class="filter-item" />
      <el-input v-model="listQuery.orderNumber" placeholder="订单编号" style="width: 200px;" class="filter-item" />
      <el-input v-model="listQuery.customerName" placeholder="客户名称" style="width: 200px;" class="filter-item" />
      <el-date-picker
        v-model="listQuery.deliveryDate"
        type="daterange"
        range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="交货日期"
        end-placeholder="交货日期"
        @change="changeDate"
      />
      <el-select v-model="listQuery.deliveryMethod" default-first-option placeholder="送货方式" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in deliveryMethod" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-date-picker
        v-model="listQuery.signingDate"
        type="daterange"
        range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="签订日期"
        end-placeholder="签订日期"
        @change="changeSigningDate"
      />
      <el-input v-model="listQuery.applicant" placeholder="申请人" style="width: 200px;" class="filter-item" />
      <el-date-picker
        v-model="listQuery.applicationTime"
        type="daterange"
        range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="申请时间"
        end-placeholder="申请时间"
        @change="changeApplicationTime"
      />
      <el-select v-model="listQuery.applicationStatus" default-first-option placeholder="申请状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in applicationStatus" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="listQuery.approver" placeholder="审核人" style="width: 200px;" class="filter-item" />

      <el-select v-model="listQuery.approvalStatus" default-first-option placeholder="审核状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in approvalStatus" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="resetHandler">
        重置
      </el-button>
    </div>
    <div style="margin-bottom: 10px;">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="openDialog">
        添加
      </el-button>
      <el-popconfirm
        :title="`是否确认删除销售合同编号为 ${ids} 的数据项`"
        @onConfirm="removeData(ids)"
      >
        <el-button slot="reference" :disabled="!ids.length" class="filter-item" type="danger" icon="el-icon-delete">
          删除
        </el-button>
      </el-popconfirm>
    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column align="center" label="编号">
        <template slot-scope="scope">
          {{ (listQuery.page - 1) * listQuery.size + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同编号" prop="salesOrder.id" />
      <el-table-column align="center" label="客户名称" prop="salesOrder.customerName" />
      <el-table-column align="center" label="联系人" prop="contactPerson" />
      <el-table-column align="center" label="金额合计" prop="salesOrder.totalAmount" />
      <el-table-column align="center" label="交货日期" prop="salesOrder.deliveryDate" />
      <el-table-column align="center" label="申请人" prop="applicant" />
      <el-table-column align="center" label="申请时间" prop="applicationTime" />
      <el-table-column align="center" label="申请状态" prop="applicationStatus">
        <template slot-scope="{row}">
          <el-link v-show="row.applicationStatus == 0" type="primary">未提交</el-link>
          <el-link v-show="row.applicationStatus == 1" type="danger">待审核</el-link>
          <el-link v-show="row.applicationStatus == 2" type="success">已审核</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核人" prop="approver" />
      <el-table-column align="center" label="审核时间" prop="approvalTime" />
      <el-table-column align="center" label="审核状态" prop="approvalStatus">
        <template slot-scope="{row}">
          <el-tag v-show="row.approvalStatus == 0" type="success">通过</el-tag>
          <el-tag v-show="row.approvalStatus == 1" type="danger">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="130" label="操作">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" circle @click="openDialog(row)" />
          <el-button type="danger" icon="el-icon-delete" circle @click="removeHandler(row.id)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form">
        <el-form-item label="订单编号" :label-width="formLabelWidth">
          <el-input
            v-model="form.orderNumber"
            :disabled="true"
          />
          <el-button type="primary" size="small" title="选择销售订单" @click="openMarketOrderDialog">选择</el-button>
        </el-form-item>
        <el-form-item label="送货方式" :label-width="formLabelWidth">
          <el-select v-model="form.deliveryMethod" placeholder="送货方式" clearable>
            <el-option v-for="item in deliveryMethod" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" :label-width="formLabelWidth">
          <el-input v-model="form.shippingAddress" />
        </el-form-item>
        <el-form-item label="联系人" :label-width="formLabelWidth">
          <el-input v-model="form.contactPerson" />
        </el-form-item>
        <el-form-item label="联系方式" :label-width="formLabelWidth">
          <el-input v-model="form.contactInformation" />
        </el-form-item>
        <el-form-item label="签订日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.signingDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remarks" type="textarea" :rows="3" />
        </el-form-item>
        <el-divider>
          <span>
            合同明细信息
            <el-tooltip effect="dark" content="明细表中带着圆点的序号，只有在点击“确定”之后，数据才会真正保存哦" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
        </el-divider>
        <el-form-item label="编号" :label-width="formLabelWidth">
          <el-input v-model="detailForm.id" disabled />
        </el-form-item>
        <el-form-item label="产品" :label-width="formLabelWidth">
          <el-input v-model="detailForm.materialName" disabled />
          <el-button size="mini" type="primary" title="选择物料档案" @click="openRecordDialog">选择</el-button>
        </el-form-item>
        <el-form-item label="订货数量" :label-width="formLabelWidth">
          <el-input v-model="detailForm.orderQuantity" />
        </el-form-item>
        <el-form-item label="金额" :label-width="formLabelWidth">
          <el-input v-model="detailForm.totalAmount" />
        </el-form-item>
        <el-form-item label="待处理" :label-width="formLabelWidth">
          <el-button :disabled="!detailForm.id" size="small" style="width: 100%;" type="primary" title="添加一条新的订单明细信息" @click="addOrderDetail">添加</el-button>
        </el-form-item>
        <el-table
          :data="form.salesContractMaterials"
          style="width: 100%"
        >
          <!-- <el-table-column label="序号" prop="id" /> -->
          <el-table-column align="center" label="序号" prop="id">
            <template slot-scope="scope">
              <el-badge :hidden="scope.row.id != ''" is-dot class="badge-dot">
                {{ scope.$index + 1 }}
              </el-badge>
            </template>
          </el-table-column>
          <el-table-column label="产品" prop="materialName" />
          <el-table-column label="型号" prop="version" />
          <el-table-column label="规格" prop="standard" />
          <el-table-column label="单位" prop="unit" />
          <el-table-column label="单价" prop="price" />
          <el-table-column label="订货数量" prop="orderQuantity" />
          <el-table-column label="金额" prop="totalAmount" />
          <el-table-column label="备注" prop="remark" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="removeMarketDetail(scope.$index, scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!-- 编辑弹出框 -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 销售订单对话框 -->
    <el-dialog title="销售订单" :visible.sync="marketOrderDialogVisible">
      <div>
        <el-input v-model="marketOrderData.listQuery.id" placeholder="订单编号" style="width: 140px;margin-right: 5px;" />
        <el-input v-model="marketOrderData.listQuery.customerName" placeholder="客户名称" style="width: 140px;margin-right: 5px;" />
        <el-button type="primary" icon="el-icon-search" @click="handleMarketOrderFilter">
          {{ $t('table.search') }}
        </el-button>
      </div>
      <el-table :data="marketOrderData.list">
        <el-table-column align="center" label="编号">
          <template slot-scope="scope">
            {{ (marketOrderData.listQuery.page - 1) * marketOrderData.listQuery.size + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单编号" prop="id" />
        <el-table-column align="center" label="客户名称" prop="customerName" />
        <el-table-column align="center" label="金额合计" prop="totalAmount" />
        <el-table-column align="center" label="交货日期" prop="deliveryDate" />
        <el-table-column align="center" label="操作" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" :disabled="form.orderNumber === row.id" @click="chooseMarketOrder(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="marketOrderData.total > 0" :total="marketOrderData.total" :page.sync="marketOrderData.listQuery.page" :limit.sync="marketOrderData.listQuery.size" @pagination="getMarketOrderList" />
    </el-dialog>

    <!-- 物料档案对话框 -->
    <el-dialog title="选择物料档案" :visible.sync="recordDialogVisible">
      <el-row>
        <el-col :span="4">
          <el-tree :data="recordData.treeData" :props="recordData.defaultProps" @node-click="handleRecordNodeClick" />
        </el-col>
        <el-col :span="20">
          <el-table :data="recordData.list">
            <el-table-column align="center" label="编号">
              <template slot-scope="{row}">
                {{ row.id }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="物料编码">
              <template slot-scope="{row}">
                {{ row.materialEncoding }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="物料名称">
              <template slot-scope="{row}">
                {{ row.materialName }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="型号">
              <template slot-scope="{row}">
                {{ row.version }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="规格">
              <template slot-scope="{row}">
                {{ row.standard }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位">
              <template slot-scope="{row}">
                {{ row.unit }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="单价">
              <template slot-scope="{row}">
                {{ row.price }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="类型">
              <template slot-scope="{row}">
                <el-tag size="mini" :type="row.type === 1 ? 'info' : ''">
                  {{ row.type === 1 ? '原料' : '成品' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="备注">
              <template slot-scope="{row}">
                {{ row.remark }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right">
              <template slot-scope="{row}">
                <!-- 对话框表单中的物料答案 和 对话框物料档案中的某一项一致，按钮便显示禁用 -->
                <!-- :disabled="form.salesContractMaterials && form.salesContractMaterials.id == row.id" -->
                <el-button type="primary" @click="chooseRecord(row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="recordData.total > 0" :total="recordData.total" :page.sync="recordData.listQuery.page" :limit.sync="recordData.listQuery.size" @pagination="getRecordList" />
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { fetchList, remove, save, edit } from '@/api/market-contract'
import { fetchList as recordFetchList } from '@/api/material-record'
import { fetchList as orderFetchList } from '@/api/market-order'
const defaultListQuery = {
  page: 1,
  size: 10,
  id: '',
  orderNumber: '',
  customerName: '',
  deliveryDate: '',
  deliveryMethod: null,
  applicationTime: '',
  signingDate: '',
  applicant: '',
  applicationStatus: null,
  approvalStatus: null,
  approver: ''
}
export default {
  name: 'MarketContract',
  components: { Pagination },
  data() {
    return {
      // 功能标题
      title: '销售合同',
      tableKey: 0,
      listLoading: true,
      // 查询参数
      listQuery: defaultListQuery,
      // 交货日期
      deliveryDate: '',
      // 签订日期
      signingDate: '',
      // 申请日期
      applicationTime: '',
      // 表格数据
      list: [],
      // 总数
      total: 0,
      // 对话框显示
      dialogFormVisible: false,
      // 对话框宽度
      formLabelWidth: '120px',
      // 表单
      form: {},
      // 对话框标题
      dialogTitle: '',
      // 待添加明细信息
      detailForm: {},

      deliveryMethod: [
        {
          key: '0',
          label: '快递'
        },
        {
          key: '1',
          label: '物流'
        }
      ],
      applicationStatus: [
        { key: '0', label: '未提交' },
        { key: '1', label: '待审核' },
        { key: '2', label: '已审核' }
      ],
      approvalStatus: [
        { key: '0', label: '通过' },
        { key: '1', label: '驳回' }
      ],
      // 物料档案数据
      recordData: {
        // 查询参数
        listQuery: {
          page: 1,
          size: 10,
          type: undefined
        },
        // 总数
        total: 0,
        list: null,
        // 树形控件数据
        treeData: [
          {
            label: '分类',
            children: [
              {
                label: '零件',
                value: 1
              },
              {
                label: '成品',
                value: 0
              }
            ]
          }
        ],
        // 树形控件属性
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      // 选择物料档案对话框是否显示
      recordDialogVisible: false,
      // 选择销售订单对话框是否显示
      marketOrderDialogVisible: false,
      // 销售订单数据
      marketOrderData: {
        // 查询参数
        listQuery: {
          page: 1,
          size: 10,
          id: '',
          customerName: ''
        },
        // 总数
        total: 0,
        list: []
      },
      // 复选框选中的id数组
      ids: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 交货日期关闭触发
     * @param { Array } value 数组
     */
    changeDate(value) {
      this.deliveryDate = value.join('|')
    },
    changeApplicationTime(value) {
      this.applicationTime = value.join('|')
    },
    changeSigningDate(value) {
      this.signingDate = value.join('|')
    },
    /**
     * 查询
     */
    handleFilter() {
      this.listQuery.deliveryDate = this.deliveryDate
      this.listQuery.applicationTime = this.applicationTime
      this.listQuery.signingDate = this.signingDate
      this.getList()
    },
    /**
     * 重置
     */
    resetHandler() {
      this.listQuery = {
        page: 1,
        size: 10,
        id: '',
        orderNumber: '',
        customerName: '',
        deliveryDate: '',
        deliveryMethod: null,
        applicationTime: '',
        signingDate: '',
        applicant: '',
        applicationStatus: null,
        approvalStatus: null,
        approver: ''
      }
      this.deliveryDate = ''
      this.applicationTime = ''
      this.signingDate = ''
    },
    getList() {
      fetchList(this.listQuery).then(res => {
        const { data } = res
        console.log(data.data)
        this.total = data.total
        this.list = data.data
        // 切割字符串转成数组
        this.listQuery.deliveryDate = this.listQuery.deliveryDate instanceof Array ? this.listQuery.deliveryDate.split('|') : ''
        this.listQuery.applicationTime = this.listQuery.applicationTime instanceof Array ? this.listQuery.applicationTime.split('|') : ''
        this.listQuery.signingDate = this.listQuery.signingDate instanceof Array ? this.listQuery.signingDate.split('|') : ''
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 开启对话框
     * @param {*} row 行数据
     */
    openDialog(row) {
      this.dialogFormVisible = true
      this.form = {}
      this.detailForm = {}
      if (row.id) {
        this.dialogTitle = `修改${this.title}`
        this.form = { ...row }
        // 返回 salesContractMaterials.id 不为 '' 的数据
        this.form.salesContractMaterials = this.form.salesContractMaterials.filter(item => item.id !== '')
      } else { // 新增
        this.dialogTitle = `添加${this.title}`
      }
    },
    // 提交表单
    submitForm() {
      if (this.form.id) {
        console.log('修改')
        this.modifyData()
      } else {
        console.log('新增')
        this.saveData()
      }
    },
    saveData() {
      this.form.applicant = this.form.contactPerson
      this.form.applicationStatus = 1 // 待审核
      this.form.applicationTime = this.form.signingDate
      this.form.isDeleted = 0 // 逻辑删除默认值，防止 后端接收为null
      save(this.form).then(res => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
      })
    },
    modifyData() {
      this.form.applicant = this.form.contactPerson
      this.form.applicationStatus = 1 // 待审核
      this.form.applicationTime = this.form.signingDate
      edit(this.form).then(res => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 5000
        })
      }).finally(() => {
        this.getList()
      })
    },
    /**
     * 打开选择销售订单对话框
     */
    openMarketOrderDialog() {
      // 显示选择销售订单对话框
      this.marketOrderDialogVisible = !this.marketOrderDialogVisible
      this.getMarketOrderList()
    },
    /**
     * 获取销售订单列表
     */
    getMarketOrderList() {
      orderFetchList(this.marketOrderData.listQuery).then(res => {
        const { data } = res
        console.log(res)
        this.marketOrderData.list = data.data
        this.marketOrderData.total = data.total
      })
    },
    // 选择销售订单对话框
    chooseMarketOrder(row) {
      console.log(row)
      this.form.orderNumber = row.id
      // 关闭对话框
      this.marketOrderDialogVisible = false
      this.$message({
        message: '销售订单选择成功',
        type: 'success'
      })
    },
    // 销售订单搜索
    handleMarketOrderFilter() {
      this.getMarketOrderList()
    },
    /**
     * 打开选择物料对话框
     */
    openRecordDialog() {
      // 显示选择物料对话框
      this.recordDialogVisible = !this.recordDialogVisible
      this.getRecordList()
    },
    /**
     * 获取物料档案列表
     */
    getRecordList() {
      recordFetchList(this.recordData.listQuery).then(resp => {
        const { data } = resp
        this.recordData.list = data.list
        this.recordData.total = data.total
      })
    },
    /**
     * 点击tree节点触发
     * @param {*} data 所点击的数据
     */
    handleRecordNodeClick(data) {
      // 赋值
      this.recordData.listQuery.type = data.value
      this.getRecordList()
    },
    /**
     * 选择物料
     * @param {*} row 当前选中行的数据
     */
    chooseRecord(row) {
      // 赋值给表单中的 待添加明细中
      this.detailForm = { ...row }
      this.detailForm.materialsId = row.id
      // 关闭物料选择对话框
      this.recordDialogVisible = !this.recordDialogVisible
      this.$message({
        message: '物料选择成功',
        type: 'success'
      })
    },
    // 添加新的订单明细记录
    addOrderDetail() {
      // 未保存到数据库的数据id置空，便可分辨出，新加入的数据
      this.detailForm.id = ''
      if (!this.form.salesContractMaterials) {
        // 初始化数组
        this.form.salesContractMaterials = []
      }
      this.form.salesContractMaterials.push(this.detailForm)
      console.log(this.form.salesContractMaterials)
      this.detailForm = {}
      this.$message({
        message: '订单明细添加成功',
        type: 'success'
      })
    },
    // 删除销售明细
    removeMarketDetail(index, id) {
      this.$confirm(`是否确认删除${id !== '' ? '销售合同编号为' + id : '“新”加入'}的数据项`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 1. 删除临时数据 id = ''
        if (id === '') {
          console.log(index, '临时数据')
          // 移除数组中的元素
          this.form.salesContractMaterials.splice(index, 1)
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        } else {
          // 2. 删除数据库中的数据
          console.log('数据库中的数据')
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 选中改变触发
     * @param { Array } val 选中的行数据
     */
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id)
    },
    // 单个删除
    removeHandler(id) {
      // console.log(ids)
      this.$confirm(`是否确认删除销售合同编号为 ${id} 的数据项`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(id)
        this.removeData([id])
      }).catch(() => {})
    },
    // 执行删除
    removeData(ids) {
      remove(ids).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).finally(() => {
        this.getList()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.badge-dot {
  margin-top: 10px;
}
</style>
